const db = require('../db/index.js');


//提交反馈
exports.submitFeedback = (req, res) => {
    const { student_id,type,title,content } = req.body;
    const create_time = new Date();
    const status = 0;
    const sql = 'insert into feedback set ?';
    db.query(sql, { student_id,type,title,content,status,create_time }, (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) {
            return res.cc('反馈失败！');
        }
        res.send({
            status: 0,
            message: '反馈成功！'
        })
    });
}

//获取反馈列表（管理员版）
exports.getFeedbackList = (req, res) => {
    const { pager } = req.body;
    const pageSize = 10; // 可配置的分页大小
    const offset = (pager - 1) * pageSize;

    // 查询总数
    const countSql = 'select count(*) as total from feedback';
    const dataSql = 'select * from feedback limit ? offset ?';

    // 先查询总数
    db.query(countSql, (err, countResult) => {
        if (err) return res.cc(err);

        // 查询分页数据
        db.query(dataSql, [pageSize, offset], (err, result) => {
            if (err) return res.cc(err);

            res.send({
                status: 0,
                message: '获取反馈列表成功！',
                data: result,
                total: countResult[0].total,
                pageSize,
                currentPage: pager
            });
        });
    });
}

//处理反馈
exports.handleFeedback = (req, res) => {
    const { id,solution } = req.body;
    const update_time = new Date();
    const status = 1;
    const sql = 'update feedback set status=?,solution=?,create_time=? where id=?';
    db.query(sql, [status,solution,update_time,id], (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) {
            return res.cc('处理反馈失败！');
        }
        res.send({
            status: 0,
            message: '处理反馈成功！'
        })
    });
}
//获取反馈列表（个人版）
exports.getFeedbackListByMe = (req, res) => {
    const { pager,student_id } = req.body;
    const pageSize = 10; // 可配置的分页大小
    const offset = (pager - 1) * pageSize;

    // 查询总数
    const countSql = 'select count(*) as total from feedback where student_id = ?';
    const dataSql = 'select * from feedback where student_id = ? limit ? offset ?';

    // 先查询总数
    db.query(countSql,[student_id], (err, countResult) => {
        if (err) return res.cc(err);

        // 查询分页数据
        db.query(dataSql, [student_id,pageSize, offset], (err, result) => {
            if (err) return res.cc(err);

            res.send({
                status: 0,
                message: '获取反馈列表成功！',
                data: result,
                total: countResult[0].total,
                pageSize,
                currentPage: pager
            });
        });
    });
}

